import React, {useEffect, useState} from 'react';
import ProForm, {ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import {Modal, message, Cascader, Form, Input, Upload, Button, Avatar, Image} from 'antd';
import {addUser, editUser, getUserInfo} from '@/services/user';
import {getRegionList} from '@/services/setting';
import {UploadOutlined, UserOutlined} from '@ant-design/icons';
import styles from './index.less';

const Edit = (props) => {
  const {isModalVisible, isShowModal, actionRef, editId} = props;
  const [regionData, setRegionData] = useState([]); // 地区数据
  const [avatar, setAvatar] = useState();
  const [visible, setVisible] = useState(false);

  const [formLayout] = useState('horizontal');

  const title = editId === null ? '添加用户' : '编辑用户';

  const formItemLayout =
    formLayout === 'horizontal' ? {labelCol: {span: 4}, wrapperCol: {span: 20}} : null;

  useEffect(() => {
    getRegionData();
  }, []);

  /**
   * 获取数据
   * 作者：糜家智
   * 时间：2021/8/2 18:03
   */
  const getData = async () => {
    const res = await getUserInfo({
      member_id: editId,
    });

    if (res.data.region_id == ''){
      res.data.region_id = null
    }else {
      // 处理地区
      res.data.region_id = res.data.region_id.split(',');
      res.data.region_id.forEach((item, index) => {
        res.data.region_id[index] = Number(item);
      });
    }

    setAvatar(res.data.avatar);
    return res.data;
  };

  /**
   * 获取地区数据
   * 作者：糜家智
   * 时间：2021/8/2 18:03
   */
  const getRegionData = () => {
    if (!localStorage.getItem('treeRegionData')) {
      getRegionList({
        type: 'tree',
      }).then((res) => {
        setRegionData(res.data);
        localStorage.setItem('treeRegionData', JSON.stringify(res.data));
      })
    } else {
      setRegionData(JSON.parse(localStorage.getItem('treeRegionData')));
    }
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/18 17:32:00
   * 功能：提交按钮
   */
  const handleSubmit = async (values) => {
    const data = values;
    // 转换地区数组
    if (data.region_id) {
      data.region_id = data.region_id.toString();
    }

    let res = {};
    if (editId === null) {
      res = await addUser(data);
    } else {
      data.member_id = editId;
      res = await editUser(data);
    }

    if (res.code === 200) {
      message.success(res.msg);
      actionRef.current.reload();
      isShowModal(false);
    }
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/19 16:07:41
   * 功能：头像配置
   */
  const avatarProps = {
    name: 'avatar_file',
    action: '/admin/Member/avatar',
    headers: {
      AdminToken: localStorage.getItem('access_token') || '',
    },
    accept: '.jpg,.png,.jpeg',
    data: {
      member_id: editId,
    },
    showUploadList: false,
    beforeUpload(file) {
      // console.log(file.size)
      if (file.size > 102400) {
        message.warning('图片不可大于100k~');
        return false;
      }
    },
    onChange(info) {
      if (info.file.status === 'done') {
        // message.success(`${info.file.name} file uploaded successfully`);
        let res = info.file.response;
        if (res.code === 200) {
          message.success('头像上传成功~');
          setAvatar(res.data.avatar);
          actionRef.current.reload();
        } else {
          message.error(res.msg);
        }
      } else if (info.file.status === 'error') {
        message.error('头像上传失败！');
      }
    },
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/19 16:13:31
   * 功能：头像组件
   */
  function avatarPro() {
    return (
      <Form.Item label="头像">
        <div className={styles.editAvatar}>
          <Avatar
            size={110}
            icon={<UserOutlined/>}
            src={avatar}
            onClick={() => setVisible(true)}
          />

          <Image
            width={200}
            style={{display: 'none'}}
            preview={{
              visible,
              src: avatar,
              onVisibleChange: (value) => {
                setVisible(value);
              },
            }}
          />

          <Upload {...avatarProps}>
            <Button className={styles.btnUpload} icon={<UploadOutlined/>}>
              更换头像
            </Button>
          </Upload>

          <span className={styles.desc}>jpg、png图片，小于100KB，宽高1:1</span>
        </div>
      </Form.Item>
    );
  }

  return (
    <Modal
      title={title}
      visible={isModalVisible}
      onCancel={() => isShowModal(false)}
      footer={null}
      destroyOnClose={true}
    >
      <ProForm
        onFinish={(values) => handleSubmit(values)}
        request={
          editId == null
            ? () => {
              return {sort: 50};
            }
            : () => getData()
        }
        {...formItemLayout}
        layout={formLayout}
      >
        {editId === null ? '' : avatarPro()}
        <ProFormText
          name="username"
          label="账号"
          tooltip="账号用英文和字母"
          placeholder="请输入账号"
          rules={[{required: true, message: '账号不能为空'}]}
        />
        <ProFormText
          name="nickname"
          label="昵称"
          placeholder="请输入昵称"
          rules={[{required: true, message: '昵称不能为空'}]}
        />
        {editId === null ? (
          <ProFormText.Password
            name="password"
            label="密码"
            placeholder="请输入密码"
            rules={[
              {required: true, message: '密码不能为空'},
              {type: 'string', min: 6, message: '密码最小6位'},
            ]}
          />
        ) : (
          ''
        )}
        <Form.Item
          name="phone"
          label="手机"
          rules={[
            {
              required: true,
              max: 11,
              message: '请输入正确的手机号',
              pattern: /^1[3456789]\d{9}$/,
            },
          ]}
        >
          <Input placeholder="请输入手机" maxLength={11}/>
        </Form.Item>
        <ProFormText
          name="email"
          label="邮箱"
          placeholder="请输入邮箱"
          rules={[
            {required: true, message: '邮箱不能为空'},
            {type: 'email', message: '邮箱格式不对'},
          ]}
        />
        <Form.Item name="region_id" label="地区">
          <Cascader
            fieldNames={{label: 'region_name', value: 'region_id'}}
            options={regionData}
          />
        </Form.Item>
        <ProFormTextArea name="remark" label="备注" placeholder="请输入备注"/>
        <ProFormText name="sort" label="排序" placeholder="请输入排序"/>
      </ProForm>
    </Modal>
  );
};

export default Edit;
